﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Chenglin.WPChildrenDrug.Models;

namespace Chenglin.WPChildrenDrug
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            ShowDataInStackPanel(commonDrugsContainer, App.Drugs.Data);

            // Hook event handlers
            searchInputTextBox.TextChanged += SearchInputTextBox_TextChanged;
        }

        private void SearchInputTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            string text = ((TextBox)sender).Text;
            if (text != null)
            {
                text = text.Trim();
            }

            if (string.IsNullOrEmpty(text))
            {
                // clear all existing contents
                searchResultContainer.Children.Clear();
            }
            else
            {
                var results = App.Drugs.Search(text);
                if (results == null || results.Length == 0)
                {
                    // No matching results found. We're going to clear all existing contents
                    searchResultContainer.Children.Clear();
                }
                else
                {
                    ShowDataInStackPanel(searchResultContainer, results);
                }
            }
        }

        private void ShowDataInStackPanel(StackPanel container, Drug[] data)
        {
            // Clear all existing content first
            container.Children.Clear();

            foreach (var d in data)
            {
                Button button = new Button();
                button.Content = d.Name;
                button.Style = (Style)Resources["CustomButtonStyle"];
                button.Tap += DrugNameButton_Tap;

                container.Children.Add(button);
            }
        }

        private void DrugNameButton_Tap(object sender, GestureEventArgs e)
        {
            Button button = (Button)sender;
            Uri pageUri = new Uri("/DrugInfoPage.xaml?n=" + HttpUtility.UrlEncode((string)button.Content), UriKind.Relative);
            NavigationService.Navigate(pageUri);
        }
    }
}